package cn.com.chengmandian.bike.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.com.chengmandian.bike.constants.FaultBillDealCreateType;
import cn.com.chengmandian.bike.constants.FaultBillInfoStatus;
import cn.com.chengmandian.bike.constants.FaultBillType;
import cn.com.chengmandian.bike.dto.FaultBillInfoDto;
import cn.com.chengmandian.bike.dto.FaultBillInfoForm;
import cn.com.chengmandian.bike.dto.FaultBillInfoHandleForm;
import cn.com.chengmandian.bike.model.*;
import cn.com.chengmandian.bike.mapper.EbFaultBillInfoMapper;
import cn.com.chengmandian.bike.model.vo.FaultBillInfoVo;
import cn.com.chengmandian.bike.service.*;
import cn.com.chengmandian.bike.utils.WxMiniService;
import cn.com.chengmandian.core.common.constants.CommonConstant;
import cn.com.chengmandian.core.common.utils.BillNoUtil;
import cn.com.chengmandian.core.redis.cache.AgentParamCacheService;
import cn.com.chengmandian.core.web.exceptions.BadResponseException;
import cn.com.chengmandian.core.web.pojo.AgentInfo;
import cn.com.chengmandian.core.web.pojo.AgentUser;
import cn.com.chengmandian.core.web.pojo.BikeParam;
import cn.com.chengmandian.service.bike.BikeCommonClient;
import cn.com.chengmandian.service.bike.constants.MessageBusinessTypeEnum;
import cn.com.chengmandian.service.bike.constants.MessageChannelEnum;
import cn.com.chengmandian.service.bike.form.MessageAddForm;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;

/**
 * <p>
 * 电单车运营-订单问题工单 服务实现类
 * </p>
 *
 * @author AutoGenerator
 * @since 2024-05-29
 */
@Slf4j
@Service
public class EbFaultBillInfoServiceImpl extends ServiceImpl<EbFaultBillInfoMapper, EbFaultBillInfo> implements IEbFaultBillInfoService {

    @Autowired
    private AgentParamCacheService agentParamCacheService;
    @Autowired
    private IEbMemberInfoService memberInfoService;
    @Autowired
    private WxMiniService wxMiniService;
    @Autowired
    private IEbRideOrderService rideOrderService;
    @Autowired
    private IEbFaultBillDealService faultBillDealService;

    @Autowired
    private IEbRemindRuleService remindRuleService;

    @Autowired
    private BikeCommonClient commonClient;

    @Override
    public IPage<FaultBillInfoVo> getPage(FaultBillInfoDto dto) {
        Page page = Page.of(dto.getPageNumber(), dto.getPageSize());
        return baseMapper.getPage(page, dto);
    }

    @Override
    public FaultBillInfoVo lastInfo(Integer orderId) {
        return baseMapper.lastInfo(orderId);
    }

    @Override
    public FaultBillInfoVo detail(Integer id) {
        FaultBillInfoVo vo =  baseMapper.detail(id);
        vo.setFaultBillDeals(faultBillDealService.list(new LambdaQueryWrapper<EbFaultBillDeal>()
                .eq(EbFaultBillDeal::getBillId, vo.getId())
                .orderByAsc(EbFaultBillDeal::getId)));
        return vo;
    }

    @Override
    public void sendNotice(AgentInfo agentInfo, Integer billId, String remark, String image) {
        // 工单信息
        EbFaultBillInfo faultBillInfo = this.getById(billId);
        Assert.notNull(faultBillInfo, "订单工单信息不存在");

        EbRemindRule notifyRule = remindRuleService.getNotifyRule(agentInfo.getId(), CommonConstant.THREE);
        if (notifyRule == null) {
            return;
        }

        EbMemberInfo memberInfo = memberInfoService.getById(faultBillInfo.getMemberId());

        //发送微信小程序消息
        if (notifyRule.getPushChannel().contains(CommonConstant.THREE.toString()) && notifyRule.getWxMiniTemplete() != null) {
            if(StrUtil.isNotBlank(memberInfo.getOpenId())) {
                MessageAddForm messageAddForm = new MessageAddForm();
                messageAddForm.setMemberId(memberInfo.getId());
                messageAddForm.setOpenId(memberInfo.getOpenId());
                messageAddForm.setWxTemplateId(notifyRule.getWxMiniTemplete());
                messageAddForm.setBusinessId(faultBillInfo.getId());
                messageAddForm.setBillId(faultBillInfo.getId());
                messageAddForm.setBillNo(faultBillInfo.getBillNo());
                messageAddForm.setTitle(FaultBillType.getByCode(faultBillInfo.getFaultType()).getName());
                messageAddForm.setContent(new StringBuilder("订单编号:").append(faultBillInfo.getOrderNo()).toString());
                messageAddForm.setStatus(FaultBillInfoStatus.getByCode(faultBillInfo.getStatus()).getName());
                messageAddForm.setRemark(remark);
                commonClient.sendOrderFeedbackWx(agentInfo.getId(), messageAddForm);
            }
        }

        // 发送用户消息
        if (notifyRule.getPushChannel().contains(CommonConstant.TWO.toString())) {
            MessageAddForm messageAddForm = new MessageAddForm();
            messageAddForm.setMemberId(memberInfo.getId());
            messageAddForm.setChannel(MessageChannelEnum.SYS);
            messageAddForm.setContent(remark);
            messageAddForm.setBusinessId(faultBillInfo.getId());
            messageAddForm.setBusinessType(MessageBusinessTypeEnum.ORDER_BILL);
            messageAddForm.setImage(image);
            commonClient.sendOrderFeedback(agentInfo.getId(), messageAddForm);
        }

    }

    @Override
    public void add(AgentInfo agentInfo, AgentUser agentUser, FaultBillInfoForm form) {
        EbRideOrder rideOrder = rideOrderService.getById(form.getOrderId());

        if(this.count(new LambdaQueryWrapper<EbFaultBillInfo>()
                .in(EbFaultBillInfo::getStatus, FaultBillInfoStatus.HANDLE.getCode(), FaultBillInfoStatus.WAIT.getCode())
                .ne(form.getId() != null, EbFaultBillInfo::getId, form.getId())
                .eq(EbFaultBillInfo::getOrderId, rideOrder.getId())) > 0) {
            throw new BadResponseException("该订单有进行中的问题反馈，不支持再次提交");
        }

        EbMemberInfo memberInfo = memberInfoService.getById(agentUser.getId());
        EbFaultBillInfo faultBillInfo = new EbFaultBillInfo();
        faultBillInfo.setBillNo(BillNoUtil.getSimpleNo("FB-"));
        faultBillInfo.setAreaId(rideOrder.getAreaId());
        faultBillInfo.setBikeId(rideOrder.getBikeId());
        faultBillInfo.setBikeNo(rideOrder.getBikeNo());
        faultBillInfo.setOrderId(rideOrder.getId());
        faultBillInfo.setOrderNo(rideOrder.getOrderNo());
        faultBillInfo.setFaultType(form.getFaultType());
        faultBillInfo.setOtherFault(form.getOtherFault());
        faultBillInfo.setImgUrl(form.getImgUrl());
        faultBillInfo.setMemberId(memberInfo.getId());
        faultBillInfo.setMemberPhone(memberInfo.getMobile());
        faultBillInfo.setMemberName(memberInfo.getName());
        if(form.getId() == null) {
            this.save(faultBillInfo);
        }else {
            faultBillInfo.setId(form.getId());
            this.updateById(faultBillInfo);
        }

        // 更新订单反馈处理状态
        if(!CommonConstant.ONE.equals(rideOrder.getFaultBillStatus())) {
            rideOrderService.update(new LambdaUpdateWrapper<EbRideOrder>()
                    .set(EbRideOrder::getFaultBillStatus, CommonConstant.ONE)
                    .eq(EbRideOrder::getId, rideOrder.getId()));
        }

        // 添加处理进度
        faultBillDealService.createRecord(faultBillInfo.getId(), FaultBillDealCreateType.MEMBER, "订单问题工单提交", form.getImgUrl(), agentUser);

        // 发送通知
        this.sendNotice(agentInfo, faultBillInfo.getId(), "订单问题工单提交成功，正在等待处理！", form.getImgUrl());
    }

    @Override
    public void complete(FaultBillInfoHandleForm form, AgentInfo agentInfo, AgentUser agentUser) {
        this.update(new LambdaUpdateWrapper<EbFaultBillInfo>()
                .set(EbFaultBillInfo::getStatus, FaultBillInfoStatus.COMPLETE.getCode())
                .set(EbFaultBillInfo::getCompleteTime, DateUtil.date())
                .eq(EbFaultBillInfo::getId, form.getId()));

        // 添加处理进度
        EbFaultBillInfo billInfo = this.getById(form.getId());
        faultBillDealService.createRecord(billInfo.getId(), FaultBillDealCreateType.MEMBER, "用户主动完结工单", billInfo.getImgUrl(), agentUser);

        // 发送通知
        EbRideOrder rideOrder = rideOrderService.getById(billInfo.getOrderId());
        this.sendNotice(agentInfo, billInfo.getId(), "您提交的订单问题处理完成！", billInfo.getImgUrl());
    }

    @Override
    public void cancel(FaultBillInfoHandleForm form, AgentInfo agentInfo, AgentUser agentUser) {
        this.update(new LambdaUpdateWrapper<EbFaultBillInfo>()
                .set(EbFaultBillInfo::getStatus, FaultBillInfoStatus.CANCEL.getCode())
                .eq(EbFaultBillInfo::getId, form.getId()));

        // 添加处理进度
        EbFaultBillInfo billInfo = this.getById(form.getId());
        faultBillDealService.createRecord(billInfo.getId(), FaultBillDealCreateType.MEMBER, "用户主动撤销工单", billInfo.getImgUrl(), agentUser);

        // 微信消息通知
        EbRideOrder rideOrder = rideOrderService.getById(billInfo.getOrderId());
        this.sendNotice(agentInfo, billInfo.getId(), "您提交的订单问题已撤销！", billInfo.getImgUrl());
    }

    @Override
    public List<FaultBillInfoVo> getOrderList(Integer orderId) {
        return baseMapper.getOrderList(orderId);
    }
}
